package io.yx.flx.install;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.io.File;

/**
 * @author YX
 * @date 2022/7/18 14:49
 */
public class InstallService {

    private static final String systemdPath = "/etc/systemd/system";

    private static final String userDir = System.getProperty("user.dir");
    private static final String javaHome = System.getProperty("java.home");

    private static final Log log = LogFactory.get(InstallService.class);

    public static void main(String[] args) {
        log.info("\nuserDir:{}\njavaHome:{}", userDir, javaHome);
        File serviceFile = new File(systemdPath + File.separator + "flx.service");
        FileUtil.touch(serviceFile);
        // 写入内容到文件
        String content = ResourceUtil.readUtf8Str("flx.service");
        content = StrUtil.replace(content, "${JAVA_HOME}", javaHome);
        content = StrUtil.replace(content, "${USER_DIR}", userDir);
        FileUtil.writeUtf8String(content, serviceFile);
        // 执行命令启动
        RuntimeUtil.exec("systemctl", "enable", "flx.service");
        RuntimeUtil.exec("systemctl", "start", "flx.service");
        RuntimeUtil.exec("systemctl", "status", "flx.service");
        log.info("已将服务加入自启动");
    }

}
